package com.lyons.easyweb.exception;

import java.sql.SQLException;
import java.util.List;

import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import com.lyons.easyweb.core.util.ResponseData;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(value = Exception.class)
	public ResponseData exception(Exception e) {
		log.error("Exception,{},{}", e.getLocalizedMessage(), e);
		return ResponseData.fail(BaseResponseCode.SYSTEM_ERROR);
	}

	@ExceptionHandler(value = BusinessException.class)
	public ResponseData businessException(BusinessException e) {
		log.error("businessException,{},{}", e.getLocalizedMessage(), e);
		return ResponseData.fail(e.getCode(), e.getMsg());
	}

	@ExceptionHandler(value = SQLException.class)
	public ResponseData sQLExceptionException(SQLException e) {
		log.error("执行sql异常：{}", e.getMessage());
		return ResponseData.fail(404, "数据链接异常");
	}

	/**
	 * 处理validation 框架异常
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	ResponseData methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
		log.error("methodArgumentNotValidExceptionHandler bindingResult.allErrors():{},exception:{}", e.getBindingResult().getAllErrors(), e);
		List<ObjectError> errors = e.getBindingResult().getAllErrors();
		return createValidExceptionResp(errors);
	}

	private ResponseData createValidExceptionResp(List<ObjectError> errors) {
		String[] msgs = new String[errors.size()];
		int i = 0;
		for (ObjectError error : errors) {
			msgs[i] = error.getDefaultMessage();
			log.info("msg={}", msgs[i]);
			i++;
		}
		return ResponseData.fail(BaseResponseCode.METHOD_IDENTITY_ERROR.getCode(), msgs[0]);
	}

	@ExceptionHandler(MaxUploadSizeExceededException.class)
	public ResponseData maxUploadSizeExceededException(MaxUploadSizeExceededException e) {
		log.error("MaxUploadSizeExceededException,{},{}", e, e.getLocalizedMessage());
		return ResponseData.fail(BaseResponseCode.FILE_TOO_LARGE);
	}

}
